<template lang="pug">
  .div
    .div(class="flex-line center clientSelector")
      .div(class="form-client")
        div
          el-button(round @click="addClients") 请选择客户
          div(class="tag-div")
            el-tag(v-for="(tag, index) in clients" :key="index" class="tag-item" closable @close="deleteHandle(tag)") {{tag.name}}
    div.table-empty
      s-table(
        ref="productTable"
        :column="productColumn"
        v-if="productRecords.length > 0"
        :dataPops="productRecords"
      )
        template(slot="count" slot-scope="text, scope")
          el-input-number.w(:value="text" controls-position="right" :min="1" @change="val => productFormChange(val, scope.id, 'count')")
        template(slot="discountAmount" slot-scope="text, scope")
          el-input-number.w(:value="text" controls-position="right" :min="1" @change="val => productFormChange(val, scope.id, 'discountAmount')")
        template(slot="amount" slot-scope="text, scope")
          p {{scope.discountAmount * (scope.count || 1)}}
          small.c_warning 折扣：{{scope.discountAmount | toPercent(scope.standardAmount)}}
        template(slot="remark" slot-scope="text, scope")
          el-input.w(:value="text" controls-position="right" @input="val => productFormChange(val, scope.id, 'remark')")
        template(slot="action" slot-scope="text, scope")
          el-link(@click="deleteProductHandle(scope.id)" type="primary") 删除

    .div(class="flex-line pt-20 justify")
      el-button(type="success" @click="addEdit('product')")
        i(class="el-icon-plus") 按产品添加
      el-button(type="success" @click="addEdit('plan')")
        i(class="el-icon-plus") 按收费方案添加

    el-divider
    alert(type="info" v-if="productRecords.length > 0")
      p
        | 标准价格合计:
        span(v-for="(item, index) in productRecords" :key="item.id")
          small ￥
          | {{item.standardAmount | toThousandFilter}} * {{item.count}}
          span.ml5.mr5(v-if="index !== productRecords.length - 1") +
        span.ml5.mr5 =
        | {{standardAmount | toThousandFilter}}
      p
        | 实际销售合计:
        span(v-for="(item, index) in productRecords" :key="item.id")
          small ￥
          | {{item.discountAmount | toThousandFilter}} * {{item.count}}
          span.ml5.mr5(v-if="index !== productRecords.length - 1") +
        span.ml5.mr5 =
        | {{discountAmount | toThousandFilter}}
      p
        | 合同金额合计:
        span.f18.c_error
          small ￥
          | {{discountAmount | toThousandFilter}}
        el-tag.ml5.vm(type="warning" size="mini") 折扣: {{discountAmount | toPercent(standardAmount)}}

    form-box.mt16(
      ref="otherForm"
      :fields="otherFields"
      :showBtns="false"
      :layoutCol="{ xs: 12, md: 12, lg: 12 }"
    )
    .drawer-footer.tr
      el-button.gradientVertical(size="large" round :loading="submitting" @click="saveHandle") 确定
    product-table(ref="productTableRef" @getProductData="addProductData" :value="value")
    table-select(ref="tableSelect" @getPlanData="addPlanData")
    table-selector(ref="clientSelector" @sureHandle="sureHandle" :visible.sync="clientsVisible" :value="clientValues" :column="client.column" :search-config="client.searchConfig" label="客户" req-url="crm/web/clientele/find")
</template>
<script>
import { mapGetters } from 'vuex'
import TableSelector from '@/components/Basic/TableSelector'
import { clientColumn, seachConfigClient } from './config'
import tableSelect from './tableSelect'
import productTable from '../../../../operate/saleCRM/tabs/product/productTable'
import { addAll, getClasses, getProductSolutionDetail } from '../api'
import Alert from '@/components/Basic/Alert'

const productColumn = [
  {
    label: '产品名称',
    prop: 'name'
  },
  {
    label: '标准价格',
    prop: 'standardAmount'
  },
  {
    label: '销售单位',
    prop: 'unit'
  },
  {
    label: '折扣价',
    prop: 'discountAmount',
    width: '146'
  },
  {
    label: '数量',
    prop: 'count',
    width: '126'
  },
  {
    label: '总价',
    prop: 'amount',
    width: '126'
  },
  {
    label: '备注',
    prop: 'remark',
    width: '126'
  },
  {
    label: '操作',
    prop: 'action'
  }
]

export default {
  components: {
    TableSelector,
    tableSelect,
    productTable,
    Alert
  },
  data () {
    return {
      submitting: false,
      classes: [],
      clients: [],
      clientValues: [],
      clientsVisible: false,

      productColumn,
      productRecords: [], // 意向产品,
      value: []
    }
  },
  computed: {
    ...mapGetters(['user', 'curArea']),
    id () {
      return this.$route.query.id
    },
    client () {
      return {
        column: clientColumn,
        searchConfig: seachConfigClient(this.classes)
      }
    },
    // 计算意向产品总金额
    standardAmount () {
      const { productRecords } = this
      return productRecords.reduce((sum, cur) => {
        return sum + (cur.standardAmount || 0) * (cur.count || 1)
      }, 0)
    },
    // 计算意向产品折扣后总金额
    discountAmount () {
      const { productRecords } = this
      return productRecords.reduce((sum, cur) => {
        return sum + (cur.discountAmount || 0) * (cur.count || 1)
      }, 0)
    },
    otherFields () {
      return [
        {
          label: '备注',
          key: 'remark',
          type: 'textarea',
          layoutCol: { xs: 24, md: 24, lg: 24 }
        }
      ]
    }
  },
  created () {
    this.getClassList()
  },
  methods: {
    // 删除选中意向产品
    deleteProductHandle (id) {
      const { productRecords } = this
      this.productRecords = productRecords.filter(x => x.id !== id)
    },
    productFormChange (val, id, key) {
      const { productRecords } = this
      this.productRecords = productRecords.map(x => {
        if (x.id === id) {
          x[key] = val
        }
        return x
      })
    },
    // 选择产品
    addProductData (data) {
      this.productRecords = data.map(x => {
        x.discountAmount = x.standardAmount
        x.count = 1
        return x
      })
    },

    addEdit (type) {
      if (type === 'product') {
        this.value = [...this.productRecords]
        this.$refs.productTableRef.mainFun()
      } else {
        this.$refs.tableSelect.mainFun()
      }
    },
    addPlanData (data) {
      console.log(data)
      this.getProductSolution(data.id)
    },
    // 获取班级列表
    getClassList () {
      getClasses().then(res => {
        this.classes = res || []
      })
    },

    async saveHandle () {
      if (!this.clients?.length) {
        this.$message.error('请选择客户')
        return
      }
      const { productRecords, discountAmount } = this
      if (!productRecords?.length) {
        this.$message.error('请选择至少一项产品')
        return
      }
      console.log(productRecords)
      const otherValues = await this.$refs.otherForm.submitForm()
      console.log(otherValues)

      const clienteleIds = []
      this.clients.map(item => {
        clienteleIds.push(item.id)
      })

      const data = productRecords.map(item => {
        const obj = {
          productId: item.id,
          standardAmount: item.standardAmount,
          count: item.count,
          practicalAmount: item.discountAmount,
          remark: item.remark
        }
        return obj
      })

      const params = {
        products: JSON.stringify(data),
        // products,
        remark: otherValues.remark,
        createdBy: this.user.id,
        totalAmount: discountAmount,
        planId: this.id,
        clienteleIds: JSON.stringify(clienteleIds),
        footnote: '',
        term: '',
        title: ''
      }

      console.log(params)
      this.submitting = true
      addAll(params, 'post').then(res => {
        this.submitting = false
        this.$message.success('保存成功')
        this.$router.go(-1)
      }).finally(() => {
        this.submitting = false
      })
    },

    getProductSolution (id) {
      getProductSolutionDetail({ id }).then(res => {
        const data = res.products
        const list = data.map(x => {
          x.id = x.productId
          x.discountAmount = x.standardAmount
          x.count = 1
          x.name = x.productName
          return x
        })
        this.addProductRecords(list)
      })
    },

    addProductRecords (data) {
      const list = data.filter(value => {
        let flag = true
        for (const index in this.productRecords) {
          const item = this.productRecords[index]
          if (item.id === value.id) {
            flag = false
          }
        }
        return flag
      })
      this.productRecords = [...this.productRecords, ...list]
    },

    // 删除标签
    deleteHandle (tag) {
      const { clients } = this
      this.clients = [...clients.filter(x => x.id !== tag.id)]
    },

    sureHandle (data) {
      console.log(data)
      this.clients = data
    },

    addClients () {
      this.clientValues = [...this.clients]
      this.clientsVisible = true
    }
  }
}
</script>
<style lang="scss" scoped>
.tag-div{
  margin-top: 10px;
  .tag-item{
    margin-right: 10px;
    margin-top: 10px;
  }
}
.clientSelector{
  margin-bottom: 20px;
}
</style>
